from django.shortcuts import render
from . import models
# Create your views here.
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import JsonResponse
from user.models import User
from user.models import Userinfo
from user.models import Item
from user.models import Style
from user.models import Cart
# 生成Token
import random
import time
import json
import base64
import hashlib
import hmac

def listallitems(request):
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    # 每条表记录都是是一个dict对象，
    # key 是字段名，value 是 字段值
    qs = models.Item.objects.values('image', 'name', 'price', 'mill__name')
    # qs =list(qs)
    # return HttpResponse(qs)

        #     <div class="salevol">销量：2333</div>
    retStr = ''
    i=0
    # 保证从所选页面循环30此
    page = 1
    i = 1
    for item in  qs:
        if i<page: 
            i += 1
            continue
        retStr += '<div class="goods">'
        for name,value in item.items():
            if name=='image':
                retStr += f'<img src="{value}" alt="{value}"> ' 
            elif name=='name':
                retStr += f'<div class= "goodsname"> {value}</div>' 
            elif name=='price':
                retStr += f'<div class="price">&yen;{value}</div>'
            elif name=='mill__name':
                retStr += f'<div class="sellername"> <svg t="1605618008222" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2963" width="16" height="16"><path d="M889.583614 155.560962c-1.786693-7.514137-2.490727-11.777231-4.848424-15.61463l-0.001024-0.002046h-0.001023c-4.973268-7.223518-13.295817-11.962449-22.728654-11.96245h-700.596356c-9.432837 0-17.756409 4.738931-22.728654 11.96245h-0.001023l-0.001023 0.002046c-2.358721 3.837398-3.061732 8.100492-4.848425 15.61463-1.786693 7.514137-69.845765 292.554032-69.845765 292.554032v7.653307c0 46.38954 26.00835 86.708827 63.960731 106.651019v301.108872c0 17.662265 14.3181 31.980365 31.980365 31.980365h703.567014c17.662265 0 31.980365-14.3181 31.980365-31.980365V562.41932c37.95238-19.942191 63.960731-60.261479 63.960731-106.651019v-7.653307c-0.002047 0-68.062142-285.039895-69.848835-292.554032zM383.78485 831.54885V703.627389h255.842922v127.921461H383.78485z m319.80263-159.901827c0-17.662265-14.3181-31.980365-31.980366-31.980365H351.804485c-17.662265 0-31.980365 14.3181-31.980366 31.980365v159.901827H191.902658v-256.287038c28.062126-2.434445 53.350069-14.914688 72.362075-33.897017 21.267373 21.233604 50.384527 34.342156 82.45699 34.342156 32.072463 0 61.189617-13.107529 82.458013-34.342156 21.055548 21.022803 49.807383 34.072003 81.502246 34.329876v0.011256l0.068561 0.001024c0.148379 0 0.294712-0.005117 0.443092-0.005117 0.147356 0.001023 0.294712 0.005117 0.442068 0.005117l0.068562-0.001024v-0.011256c31.715329-0.257873 61.470003-13.30605 82.525551-34.329876 21.268396 21.233604 50.384527 34.342156 82.458014 34.342156 32.072463 0 61.189617-13.107529 82.45699-34.342156 19.012006 18.98233 44.299949 31.461549 72.362074 33.897017v256.287038H703.58748v-159.901827z m132.265396-159.911036c-29.943986 0-54.220902-24.536836-54.220902-54.801117 0-15.131629-12.108782-27.370371-27.080776-27.370371-14.971993 0-27.080775 12.238742-27.080775 27.370371 0 30.264281-24.276916 54.801117-54.220902 54.801117-29.943986 0-54.220902-24.536836-54.220902-54.801117 0-15.131629-12.108782-27.370371-27.080776-27.370371-14.971993 0-27.080775 12.238742-27.080775 27.370371 0 30.264281-24.276916 54.801117-54.220902 54.801117-29.943986 0-54.220902-24.536836-54.220902-54.801117 0-15.131629-12.108782-27.370371-27.080776-27.370371-14.971993 0-27.080775 12.238742-27.080775 27.370371 0 30.264281-24.276916 54.801117-54.220902 54.801117-29.943986 0-54.220902-24.536836-54.220902-54.801117 0-15.131629-12.108782-27.370371-27.080775-27.370371-14.971993 0-27.080775 12.238742-27.080776 27.370371 0 30.264281-24.276916 54.801117-54.220902 54.801117s-57.494459-33.68724-57.494459-63.951521l62.50559-255.842922h640.513955l64.508199 255.842922c-0.00307 30.264281-29.67588 63.951521-59.619865 63.951521z" p-id="2964" fill="#d81e06"></path></svg>{value}</div>'
        retStr += '<div class="salevol">销量：2333</div>'           
        retStr += '</div>'
        if i==page+30:
            i=1
            break
    return JsonResponse({'ret':0, 'data':retStr})

def listuserinfo(request):

    qs = models.Userinfo.objects.values('name', 'phone','sex', 'user__account' )
    retStr = ''
    for item in  qs:
        for name, value   in item.items():
            retStr += f'{value}'
    return HttpResponse(retStr)

def login(request):
    """
    添加解析记录
    :param request:
    :return:
    """
    if request.method == 'POST':
        # 获取表单内容
        info = json.loads(request.body.decode())
        # info = request.params['data'] 
        # account = request.POST.get('account')
        # password = request.POST.get('password')
        # 看是否有对应用户
        account = info['account']
        password = info['password']
        # return JsonResponse({'account':account, 'password':password})
        try:
            # 根据 id 从数据库中找到相应的客户记录 
            
            user = User.objects.get(account=info['account'])
        except User.DoesNotExist:
            return JsonResponse({
                'ret': '1',
                'msg': '客户不存在'
            })
        # i=0
        # for user in User:
        #     return JsonResponse({'ret':user})
        #     # if user.account == account and user.password == password:
        #         # i=2 

        # if i!=2:
        #     return {
        #         'ret': '1',
        #         'msg': '用户名或密码错误'
        #     }
        # else :
        exp=60 # token有效期 秒
        salt='suigfiugawdilgabDgew372834bhshfvcj' 
        headers = {
            'exp': int(time.time() + exp)  # 过期时间戳
        }
        first = base64.urlsafe_b64encode(json.dumps(headers, separators=(',', ':')).encode('utf-8').replace(b'=', b'')).decode('utf-8').replace('=', '')
        payload = {
            'author': 'trdthg',
            'account': account
        }
        second = base64.urlsafe_b64encode(json.dumps(payload, separators=(',', ':')).encode('utf-8').replace(b'=', b'')).decode('utf-8').replace('=', '')
        # 拼接前两部分
        first_second = f'{first}.{second}'
        # 对前面两部分签名呀
        third = base64.urlsafe_b64encode(hmac.new(salt.encode('utf-8'), first_second.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8').replace('=','')
        # 拼接签名和前两部分，就叫做token啦
        token = '.'.join([first, second, third])
        return JsonResponse({'status':'200, OK', 'ret': 0, 'msg': '登陆成功', 'token': token} )

def whetherlogin(request):
    if request.method == 'POST':
        try:
            info = json.loads(request.body.decode())
            token = info['token']
        except:
            # return HttpResponse('http://localhost/login.html')
            # return render(request,'http://localhost/login.html')
            return JsonResponse({'ret': '1', 'msg': '你没token, 😠!'})
        if token == "":
            # return render(request,'http://localhost/login.html', )
            # return HttpResponseRedirect('http://localhost/login.html')
            return JsonResponse({'ret': '1', 'msg': '你没token, 😠!'})


        salt='suigfiugawdilgabDgew372834bhshfvcj'
        headers = token.split(".")[0]
        payload = token.split(".")[1]
        sign = token.split(".")[2]
        headers_payload = f"{headers}.{payload}"
        new_sign = base64.urlsafe_b64encode(hmac.new(salt.encode('utf-8'), headers_payload.encode('utf-8'), hashlib.sha256).digest()).decode('utf-8').replace('=','')
        if new_sign == sign :
            if isinstance(payload, str):
                payload = payload.encode('ascii') 
                rem = len(payload) % 4 
            if rem > 0:
                payload += b'=' * (4 - rem)
                # 上面这一部分是解密的部分数据补全格式
            payload_data = base64.urlsafe_b64decode(payload) # 解码
            data = json.loads(payload_data) # 加载payload信息为可以通过get方法获取里面的值
            account = data.get("account") # 获取token里面的payload部分中的uid数据信息
            return JsonResponse({'ret': '0', 'account': account, 'msg': '你有token', 'token': token})
        else:
            # return render(request,'http://localhost/login.html')
            # return HttpResponse('http://localhost/login.html')
            return JsonResponse({'ret':'1', 'msg':'token失效'})
        return JsonResponse({'ret':'1', 'msg':'不支持的请求方式'})

def displaygoods(request):

    if request.method == 'POST':
        try:
            info = json.loads(request.body.decode())
            goodsname = info['goodsname']
        except: 
            return HttpResponse('━━(￣ー￣*|||━━')
        retStr = ''
        qs = models.Item.objects.values('id', 'name', 'image', 'price', 'mill__id')
        i = 0
        # item = Item.objects.get(name=goodsname)
        for item in  qs:
            for name,value in item.items():
                if name=='name' and value==goodsname :
                    i=1
                    # 现在对应的item为该商品的列
                    # 现在要找到外键id指向该商品的所有style
                    # <a href="" >
                    #     <img  width="40" height="40" ><i>A型</i>
                    # </a>
                    qs = models.Style.objects.values('style', 'item__id')
                    for style in qs:
                        for name, value in style.items():
                            if style['item__id'] == item['id']:
                                if name == 'style':
                                    retStr += f'<a href="" ><img width="40" height="40" ><i>{value}</i></a>'
                    return JsonResponse({'name':item['name'], 'price': item['price'], 'id': item['mill__id'], 'allstyle': retStr})
        if i==0:
            return JsonResponse({'msg':'没有该商品'})

def showthisstyle(request):
    # 传入style对应的item的id,以及该style的name
    if request.method == 'POST':
        try:
            info = json.loads(request.body.decode())
            goodsname = info['goodsname']
            itemid = info['itemid']
        except: 
            return HttpResponse('━━(￣ー￣*|||━━')
        retStr = ''
        qs = models.Style.objects.values('id', 'style', 'image', 'price', 'item__id')
        for style in qs:
            if str(style['item__id'])==itemid+'' and style['style']==goodsname :
                return JsonResponse({'ret':'0','itemid':style['item__id'], 'stylename':style['style'], 'imagepath':style['image'], 'price':style['price']})
        return HttpResponse("没有该商品")
    else:
        return HttpResponse("gun")

def showmyinfo(request):
     if request.method == 'POST':
        try:
            info = json.loads(request.body.decode())
            account = info['account']
        except: 
            return JsonResponse({'ret':'1', 'msg':'您未登录'})
        if account != '' :
            retStr = ''
            qs = models.User.objects.values()
            for user in qs:
                if user['account']==account:
                    # userinfo = Userinfo.objects.get(user=user['user__id'])
            # user = User.objects.filter(account=account).values()
                    userinfo = Userinfo.objects.filter(user=user['id']).values()
                    return JsonResponse({'ret':'0', 'account':account, 'password':user['password'], 'name':userinfo[0]['name'], 'phone':userinfo[0]['phone'], 'sex':userinfo[0]['sex'], 'image':userinfo[0]['image'] })
            # user = User.objects.get(account=account)
            # userid = user.user
            # userinfo = Userinfo.objects.get(user=str('user_id'))

            # for userinfo in qs:
            #     if userinfo['user__id']==
            return JsonResponse({'ret':'1', 'msg':'没有此人'})
        else:
            return JsonResponse({'ret':'1', 'msg':'您未登录'})

def changeinfo(request):
    if request.method == 'POST':
        
        info = json.loads(request.body.decode())
        account = info['account']
        newname = info['newname']
        newphone = info['newphone']
        newpassword1 = info['newpassword1']
        newpassword2 = info['newpassword2']
        
        retStr = ''
        qs = models.User.objects.values()
        for user in qs:
            if user['account']==account:
                userid = user['id']
                # userinfo = Userinfo.objects.filter(user=user['id']).values()
                if newname != '' and newphone != '' and newpassword1 != '' and newpassword2 != '' :
                    return JsonResponse({'ret':'2', 'msg':'您未填写信息'})
                if newpassword1!=newpassword2:
                    return JsonResponse({'ret':'2', 'msg':'前后密码不一致'})

                userinfo = Userinfo.objects.get(user=userid)
                if newname != '':
                    userinfo.name = newname
                if newphone != '':
                    userinfo.phone = newphone
                user = User.objects.get(account=account)
                if newpassword1 != '' and newpassword2 != '' and newpassword1==newpassword2:
                    user.password = newpassword2
                userinfo.save()
                user.save()
                return JsonResponse({'ret':'0', 'msg':'修改完成'})
        return JsonResponse({'ret':'2', 'msg':'没有此人oooomygod'})

def register(request):
    if request.method == 'POST':
        try:
            info = json.loads(request.body.decode())
            name = info['name']
            password = info['password']
            confirm = info['confirm']
        except:
            return JsonResponse({'ret':'1', 'msg':'发生错误'})
        if password != confirm :
            return JsonResponse({'ret':'1', "msg":'输入密码不一致'})
        # 随机生成11位数作为账号
        while True:
            account = random.randint(10000000000,99999999999)
            # account = str(account)
            try:
                user = User.objects.get(account=account)
            except:
                record = User.objects.create(account=str(account) ,password=str(password))
                A = User.objects.get(account = account)
                Userinfo.objects.create(name = str(name), user=A)
                return JsonResponse({'ret':'0', 'msg':f'注册成功, 请勿关闭此页面.请牢记您的用户名:{account}'})

def cart(request):
     if request.method == 'POST':
        try:
            info = json.loads(request.body.decode())
            account = info['account']
        except: 
            return JsonResponse({'ret':'1', 'msg':'您未登录'})
        if account != '' :
            retStr = ''
            qs = models.User.objects.values()
            for user in qs:
                if user['account']==account:

                    cart = Cart.objects.filter(user=user['id']).values()
                    return JsonResponse({'ret':'0', 'account':account, 'password':user['password'], 'name':userinfo[0]['name'], 'phone':userinfo[0]['phone'], 'sex':userinfo[0]['sex'], 'image':userinfo[0]['image'] })
            return JsonResponse({'ret':'1', 'msg':'没有此人'})
        else:
            return JsonResponse({'ret':'1', 'msg':'您未登录'})



